package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageBean;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.IYddLinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {
    @Autowired
    private IYddLinkService linkService;

    @GetMapping("/list")
    public ResultData list(String type, Integer page, Integer limit) {
        log.info("友情链接分页数据:当前页{},每页条数{}", page, limit);
        //构造条件分页
        Page<YddLink> pageInfo = new Page<>(page, limit);
        //条件构造器
        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        //根据不同的type值设置分页条件
        queryWrapper.eq(YddLink::getType, type);
        linkService.page(pageInfo, queryWrapper);
        PageBean<YddLink> linkPageBean = new PageBean<>();
        linkPageBean.setCurrentPage(pageInfo.getPages());
        linkPageBean.setTotalPages(pageInfo.getPages());
        linkPageBean.setCount(pageInfo.getTotal());
        linkPageBean.setPageSize(pageInfo.getSize());
        linkPageBean.setData(pageInfo.getRecords());
        return ResultData.ok("", linkPageBean);

    }

    /**
     * 新增友情链接
     *
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody YddLink yddLink) {
       /* if ("1".equals(yddLink.getType())) {
            yddLink.setImg("");
        }
        yddLink.setDefaultData(null);*/
        linkService.save(yddLink);
        return ResultData.ok("", null);

    }

    /**
     * 根据id查询数据,数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(Integer id) {
        YddLink yddLink = linkService.getById(id);
        return ResultData.ok("", yddLink);
    }

    /**
     * 修改数据
     *
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddLink yddLink) {
        LambdaQueryWrapper<YddLink> linkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkLambdaQueryWrapper.eq(YddLink::getId, yddLink.getId());
        linkService.update(yddLink, linkLambdaQueryWrapper);
        return ResultData.ok("", null);
    }

    @GetMapping("/del")
    public ResultData delete(Integer id) {
        //先查询出链接数据
        YddLink yddLink = linkService.getById(id);
        if ("1".equals(yddLink.getDefaultData())) {
            throw new BusinessException("系统默认数据,不允许删除！");
        }
        linkService.removeById(id);
        return ResultData.ok("", null);
    }

}
